import React, { Component } from 'react';
import Search from '../../common/compont/Search';
import { LgSearch, LgButton, LgSelect, LgPaginationA, lgAlert } from 'lancoo-web-ui';
import './scss/NewsList.scss';
import $ from 'jquery';
import { getData, getRealPath, getQueryVariable, putData1, delData } from '../../common/js/fetch';
import Alert from '../../common/compont/alert_dialog_wrapper';
import { message, Modal, Pagination, Select } from 'antd';
import CreateNews from './CreateNews';
import { createHashHistory } from 'history';
const { Option } = Select

class Newslists extends Component {
    constructor(props) {
        super(props);
        this.state = {
            NewsList: [],
            Newstype: '全部类别',
            NewsTypeList: [],
            isMouseOut: false,
            isMouseOut1: false,
            chooseOne: false,
            visible: false,
            NoticeMain: 0,
            Keyword: '',
            PageIndex: 1,
            pageSize: 10,
            total: 0,
            openAddEvent: false,
            message: '',
            isOpen: false,
            button: 0,
            NewsID: '',
            changeIdx: 0,
            NewsTitle: '发布新闻资讯',
            sortType: 0,
            UserID: sessionStorage.getItem('UserID') ? sessionStorage.getItem('UserID') : '',
            UserType: sessionStorage.getItem('UserType') ? sessionStorage.getItem('UserType') : '',
            UserClass: sessionStorage.getItem('UserClass') ? sessionStorage.getItem('UserClass') : '',
            typeId: '',
            releaseStatus: '',
            schoolId: sessionStorage.getItem('schoolId'),
            user: '',
            searchText: '',
            selectValue: '全部类型',
            selectValueB: '全部状态',
            datalistB: [
                {
                    text: "全部状态",
                    status: ''
                },
                {
                    text: "已发布",
                    status: '1'
                },
                {
                    text: "未发布",
                    status: '0'
                },
            ],
            systemInfo: JSON.parse(sessionStorage.getItem('systemInfo')),
            newsName: '',
        }
        this.getChildrenMsg = this.getChildrenMsg.bind(this);
        this.hideModal = this.hideModal.bind(this);
        this.onChangePage = this.onChangePage.bind(this);
        this.onChangePage1 = this.onChangePage1.bind(this);

        this.handleKeyPress = this.handleKeyPress.bind(this);
        this.handleQueryChange = this.handleQueryChange.bind(this);
        this.handleSearch = this.handleSearch.bind(this);
    }
    // 挂载后
    componentDidMount() {
        //获取新闻资讯列表
        this.getNewsList('');
        this.getTypeList();
    }

    addEvent(elm, event, handler) {
        if (window.attachEvent) {
            elm.attachEvent("on" + event, handler);
        } else if (window.addEventListener) {
            elm.addEventListener(event, handler);
        } else {
            elm['on' + event] = handler;
        }
    }
    getNewsList() {
        let {
            PageIndex,
            Keyword,
            UserID,
            typeId,
            releaseStatus,
            schoolId,
            Newstype,
            user,
            chooseOne,
            sortType
        } = this.state
        getData('api/news/list/page', {
            pageNum: PageIndex,
            pageSize: 10,
            keyWord: encodeURIComponent(Keyword),
            userId: chooseOne ? user : '',
            typeId: typeId,
            releaseStatus: releaseStatus,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            sortType: sortType
        }).then((res) => {
            return res.json()
        }).then((json) => {
            if (json.code == 200) {

                this.setState({
                    NewsList: json.data,
                    total: json.total,
                    // user: ''
                }, () => {
                    if (this.state.total > 10) {
                        // document.getElementsByClassName('ant-pagination-options-quick-jumper')[0].childNodes[0].nodeValue = '到'
                    }
                })
            } else {
                message.error(json.msg, 3);
            }
        })
    }

    //搜索相应的资讯
    getChildrenMsg(keyword) {
        let {
            PageIndex,
            // keyWord,
            UserID,
            typeId,
            releaseStatus,
            schoolId,
            Newstype,
            user,
            chooseOne,
            sortType
        } = this.state
        getData('api/news/list/page', {
            pageNum: 1,
            pageSize: 10,
            keyWord: encodeURIComponent(keyword),
            userId: chooseOne ? user : '',
            typeId: typeId,
            releaseStatus: releaseStatus,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            sortType: sortType
        }).then((res) => {
            return res.json()
        }).then((json) => {
            // console.log(json);
            // hide();
            if (json.code == 200 && json.data) {
                this.setState({
                    Keyword: keyword,
                    Newstype: '全部类别',
                    NewsList: json.data,
                    total: json.total,
                    // Newstype: '全部类别',
                    // PageIndex: page,
                    // chooseOne: false,
                })
            } else {
                if (json.StatusCode == 403) {
                    const history = createHashHistory();
                    history.push('/Error');
                    return
                }
                message.error(json.msg, 3);
            }
        })
    }
    createNews() {
        this.setState({
            NoticeMain: 0,
        }, () => {
            this.setState({
                visible: true,
                NewsTitle: '创建新闻资讯',
                NoticeMain: 0,
            })
            // sessionStorage.setItem('editor', 'editor');
        })

    }
    getTypeList() {
        let {
            systemInfo
        } = this.state
        //获取类型
        getData('api/news/type/send/type/list', {
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
        }).then((res) => {
            return res.json()
        }).then((json) => {
            // console.log(json);
            // hide();
            if (json.code == 200 && json.data) {
                // json.data.unshift([{ newsTypeId: '', newTypeName: '全部类别', schoolId: sessionStorage.getItem('schoolId') }]);
                let data = json.data;
                data.forEach(item => {
                    item.text = item.newTypeName;
                });
                if (systemInfo.beEdu == '1') {
                    data.unshift({ newsTypeId: '', text: '全部类型' }, { newsTypeId: '0', text: '校园资讯' });
                } else {
                    data.unshift({ newsTypeId: '', text: '全部类型' });
                }
                this.setState({
                    NewsTypeList: data,
                })
            } else {
                message.error(json.msg, 3);
            }
        })
    }


    chooseType(type) {
        this.setState({
            typeId: type,
            isMouseOut: false,
            isMouseOut1: false,
            PageIndex: 1,
            Keyword: '',
        }, () => {
            this.getNewsList('');
        })
    }
    ChooseOne() {
        if (this.state.chooseOne == true) {
            this.setState({
                chooseOne: !this.state.chooseOne,
                PageIndex: 1,
                Keyword: '',
                user: ''
            }, () => {
                this.getNewsList(this.state.user);
                this.setState({
                    user: ''
                })
            })
        } else {
            this.setState({
                chooseOne: !this.state.chooseOne,
                PageIndex: 1,
                Keyword: '',
                user: sessionStorage.getItem('UserID')
            }, () => {
                this.getNewsList(this.state.user);
            })
        }
    }
    hideModal() {
        this.setState({
            visible: false
        })
    }

    onChangePage(page = 1) {
        let $this = this;
        let {
            PageIndex,
            // keyWord,
            UserID,
            typeId,
            releaseStatus,
            schoolId,
            Newstype,
            sortType,
            user,
            chooseOne
        } = this.state
        getData('api/news/list/page', {
            pageNum: page,
            pageSize: 10,
            // keyWord: keyWord,
            userId: chooseOne ? user : '',
            typeId: typeId,
            releaseStatus: releaseStatus,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            sortType: sortType
        }).then((res) => {
            return res.json()
        }).then((json) => {
            // console.log(json);
            // hide();
            if (json.code == 200) {
                $this.setState({
                    NewsList: json.data,
                    total: json.total,
                    chooseOne: false,
                    // Newstype: '全部类别',
                    PageIndex: page,
                }, () => {
                    if (this.state.total > 10) {
                        // document.getElementsByClassName('ant-pagination-options-quick-jumper')[0].childNodes[0].nodeValue = '到'
                    }
                })
                window.scrollTo({
                    left: 0,
                    top: 100,
                    // behavior: 'smooth',
                });
            } else {
                message.error(json.msg, 3);
            }
        })
        // console.log( this.state.value);
    }
    onChangePage1(page = 1, type = '') {
        let $this = this;
        let {
            UserID,
            typeId,
            releaseStatus,
            schoolId,
            Newstype,
            sortType,
            user,
            chooseOne
        } = this.state
        getData('api/news/list/page', {
            pageNum: page,
            pageSize: 10,
            // keyWord: keyWord,
            userId: chooseOne ? user : '',
            typeId: typeId,
            releaseStatus: releaseStatus,
            eduId: JSON.parse(sessionStorage.getItem('userInfo')).eduId,
            sortType: sortType,
        }).then((res) => {
            return res.json()
        }).then((json) => {
            // console.log(json);
            // hide();
            if (json.code == 200) {
                $this.setState({
                    NewsList: json.data,
                    total: json.total,
                    PageIndex: page,
                })
                if (type !== 'sort') {
                    window.scrollTo({
                        left: 0,
                        top: 100,
                        // behavior: 'smooth',
                    });
                }
            } else {
                message.error(json.msg, 3);
            }
        })
        // console.log( this.state.value);
    }
    //跳转到详情
    OpenNewsContent(e, id, UserID, stute) {
        if (UserID !== sessionStorage.getItem('UserID') && this.state.UserClass !== '2' && stute == 0) {
            message.warn('普通管理员只能编辑自己的资讯!');
            return;
        }
        if ((UserID == sessionStorage.getItem('UserID') || this.state.UserClass == '2') && stute == 0) {
            this.EditNews(e, id);
            return
        }
        let token = getQueryVariable('lg_tk') || sessionStorage.getItem('token')

        // let url = window.location.href.split('?')[0] + '#/NewsContent?lg_tk=' + sessionStorage.getItem('token') + '&NewsID=' + id;
        let url = ''
        if (getQueryVariable('isManage') == 1) {
            url = getRealPath() + '#/NewsContent?lg_tk=' + token + '&newsId=' + id + '&lg_ic=' + getQueryVariable('lg_ic') + '&pb_id=' + UserID + '&isManage=1'
        } else {
            url = getRealPath() + '#/NewsContent?lg_tk=' + token + '&newsId=' + id + '&lg_ic=' + getQueryVariable('lg_ic') + '&pb_id=' + UserID
        }

        window.open(url, '_blank');
        let $this = this;
        if (!this.state.openAddEvent) {
            this.setState({
                openAddEvent: true
            })
            this.addEvent(window, 'message', function (e) {
                try {
                    if (e.data == 1) {
                        $this.getNewsList('');
                    }
                } catch (ex) {
                }
            }, false);
        }

    }
    //撤回新闻
    withdrawNews(e, NewsID, idx, newsTitle) {
        this.setState({
            message: `将会被撤回，您确定撤回吗？`,
            isOpen: 'true',
            button: 0,
            changeIdx: idx,
            NewsID,
            PageIndex: 1,
            newsName: newsTitle
        })
        e.stopPropagation();
        // let $this =this;

    }
    //删除新闻
    DelNews(e, NewsID, idx, newsTitle) {
        this.setState({
            message: '删除后将不可恢复，您确定删除吗？',
            isOpen: 'true',
            button: 1,
            changeIdx: idx,
            NewsID,
            PageIndex: 1,
            newsName: newsTitle
        })
        e.stopPropagation();
        // let $this =this;

    }
    //编辑新闻
    EditNews(e, NewsID) {
        e.stopPropagation();
        this.setState({
            NoticeMain: 0
        }, () => {
            getData('api/news/info//edit/detailed', {
                // UserID: sessionStorage.getItem('UserID'),
                // UserType: sessionStorage.getItem('UserType'),
                newsId: NewsID
            }).then((res) => {
                return res.json();
            }).then((json) => {
                if (json.code == 200 && json.data) {
                    this.setState({
                        visible: true,
                        NoticeMain: json.data,
                        isOpen: false,
                        NewsTitle: '编辑新闻资讯',
                    })
                } else {
                    message.error(json.msg);
                }
            })
        })

    }
    //是否弹窗的判断
    ChangeNewsFn(data) {
        console.log(data, 'data1111');
        if (data) {
            if (this.state.button == 0) {
                putData1('api/news/manage/callBack', {
                    // UserID: sessionStorage.getItem('UserID'),
                    // UserType: sessionStorage.getItem('UserType'),
                    newsId: this.state.NewsID
                }).then((res) => {
                    return res.json()
                }).then((json) => {
                    // console.log(json);
                    // hide();
                    if (json.code == 200) {
                        message.success('撤回成功')
                        let NewsList = JSON.parse(JSON.stringify(this.state.NewsList));
                        NewsList[this.state.changeIdx].ReleaseStatus = 1;
                        this.setState({
                            NewsList,
                            PageIndex: 1,
                            isOpen: false
                        }, this.getNewsList())
                    } else {
                        this.setState({
                            isOpen: false
                        })
                        message.error(json.msg, 3);

                    }
                })
            }
            if (this.state.button == 1) {
                delData('api/news/manage/delete', {
                    newsId: this.state.NewsID
                }).then((res) => {
                    return res.json()
                }).then((json) => {
                    // console.log(json);
                    // hide();
                    if (json.code == 200) {
                        if (this.state.PageIndex > 1 && this.state.NewsList.length == 1) {
                            this.onChangePage1(this.state.PageIndex - 1);
                        } else {
                            this.onChangePage1(this.state.PageIndex);
                        }

                        this.setState({
                            isOpen: false
                        })
                        message.success('删除成功~');
                    } else {
                        this.setState({
                            isOpen: false
                        })
                        message.error(json.msg, 3);

                    }
                })
            }
        } else {
            this.setState({
                isOpen: false,
            })
        }
    }
    changeSortType(type) {
        if (type == 'time') {
            this.setState({
                sortType: this.state.sortType === 0 ? 1 : 0
            }, () => {
                this.onChangePage1(this.state.PageIndex, 'sort');
            })
        } else if (type == 'read') {
            this.setState({
                sortType: this.state.sortType === 2 ? 3 : 2
            }, () => {
                this.onChangePage1(this.state.PageIndex, 'sort');
            })
        }
    }
    //分页总页数
    showTotal(total, range) {
        return `共${total}页`
    }

    handleKeyPress(event) {
        if (event.key === 'Enter') {
            this.handleSearch();
        }
    }

    handleQueryChange(event) {
        this.setState({
            Keyword: event.target.value
        });
    }

    handleSearch() {
        // 执行搜索操作
        console.log('search:', this.state.Keyword);
        this.getChildrenMsg(this.state.Keyword)
    }

    SelectOptionA = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValue: item.text,
            typeId: item.newsTypeId,
            // chooseOne: false,
            PageIndex: 1,
        }, () => {
            this.getNewsList()
        })
    }
    SelectOptionB = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValueB: item.text,
            releaseStatus: item.status,
            // chooseOne: false,
            PageIndex: 1,
        }, () => {
            this.getNewsList()
        })
    }

    //发布、保存后全部重置
    reloadType = () => {
        this.setState({
            selectValue: '全部类型',
            typeId: '',
            selectValueB: '全部状态',
            releaseStatus: '',
            // chooseOne: false,
            PageIndex: 1,
        })
    }
    //页码选择
    changePageA = (page) => {
        console.log('page', page);
        this.setState({
            PageIndex: page
        }, () => {
            this.getNewsList();
        })

    }

    //更换提示层——删除
    alertAQuestion = (e, NewsID, idx, newsTitle) => {
        this.setState({
            button: 1,
            changeIdx: idx,
            NewsID,
            PageIndex: 1,
            newsName: newsTitle
        })
        e.stopPropagation();
        let alert = lgAlert.show({
            duration: 0,
            content: <span>确定要删除<span className='high-light' title={newsTitle}>"{newsTitle}</span><span style={{ color: '#f06600' }}>"</span>吗？</span>,
            description: "资讯删除后不可恢复",
            isShowCloseBtn: true,
            tipType: 'question',
            tipMouldType: 'A',
            tipSize: 'big',
            confirmText: "确定",
            closeText: "再想想",
            showCover: true,
            coverZIndex: 1000,
            coverOpacity: 0.25,
            position: { xAxis: '50%', yAxis: '35%', showDirection: 'center', xOffset: '-50%' },
            onConfirm: () => {
                this.ChangeNewsFn(true)
                lgAlert.close(alert.index)
            }
        });
    }
    //更换提示层——撤回
    questionCallback = (e, NewsID, idx, newsTitle) => {
        this.setState({
            button: 0,
            changeIdx: idx,
            NewsID,
            PageIndex: 1,
            newsName: newsTitle
        })
        e.stopPropagation();
        let alert = lgAlert.show({
            duration: 0,
            content: <span>您确定要撤回<span className='high-light' title={newsTitle}>"{newsTitle}</span><span style={{ color: '#f06600' }}>"</span>吗？</span>,
            // description: "这是一个帮助提示描述",
            isShowCloseBtn: true,
            tipType: 'question',
            tipMouldType: 'A',
            tipSize: 'big',
            confirmText: "确定",
            closeText: "再想想",
            showCover: true,
            coverZIndex: 1000,
            coverOpacity: 0.25,
            position: { xAxis: '50%', yAxis: '35%', showDirection: 'center', xOffset: '-50%' },
            onConfirm: () => {
                this.ChangeNewsFn(true)
                lgAlert.close(alert.index)
            }
        });
    }
    render() {
        let {
            NewsTypeList,
            selectValue,
            selectValueB,
            datalistB,
            total,
            pageSize,
            PageIndex,
            systemInfo,
            newsName,
        } = this.state
        return (
            <div className='NewsList-div clearfix'>
                <div className='newsList-box'>
                    <div className='newsList-choose' >
                        <div className='div-select'>
                            <LgSelect className='select-type'
                                datalist={NewsTypeList} SelectOption={this.SelectOptionA}
                                placeholder='请选择' width={150}
                                value={selectValue}
                            ></LgSelect>
                        </div >
                        <div className='div-select div-select-status'>
                            <LgSelect className='select-type'
                                datalist={datalistB} SelectOption={this.SelectOptionB}
                                placeholder='请选择' width={150}
                                value={selectValueB}
                            ></LgSelect>
                        </div >
                        <i className={this.state.chooseOne ? 'chooseOne' : 'chooseMore'} onClick={() => { this.ChooseOne() }}></i><span className='chooseOne-span' onClick={() => { this.ChooseOne() }}>只看自己发布的</span>
                        <div style={{ display: 'inline-block', float: 'right', marginRight: '-11px' }} >
                            <LgSearch className='search-news' onSearch={(value) => this.getChildrenMsg(value)} onClear={() => this.getChildrenMsg('')}
                                value={this.state.Keyword} input={{ disabled: false, placeholder: "搜索新闻资讯标题/发布者姓名...", onChange: (e) => this.handleQueryChange(e), onKeyPress: (e) => this.handleKeyPress(e) }} ></LgSearch>
                            {/* <LgButton className='News-create-button' backgroundType='opacification' showIcon icon={<LgButton.icon.Add></LgButton.icon.Add>} type='success' onClick={() => { this.createNews() }}>
                                创建新闻资讯</LgButton> */}
                            <LgButton style={{marginLeft: '12px'}} backgroundType='opacification' showIcon icon={<LgButton.icon.Add></LgButton.icon.Add>} gradient type='success' onClick={() => { this.createNews() }}>创建新闻资讯</LgButton>
                        </div>
                    </div>
                    {this.state.NewsList && this.state.NewsList.length > 0 ? <table>
                        <thead>
                            <tr>
                                <th width="660" >标题</th>
                                <th width="140" >发布者</th>
                                <th width="225" ><b onClick={() => { this.changeSortType('time') }}>发布时间<i className={'time-sort ' + (this.state.sortType == 0 ? 'time-sort-add' : this.state.sortType == 1 ? 'time-sort-dec' : '')}></i></b></th>
                                <th width="110" ><b onClick={() => { this.changeSortType('read') }}>阅读次数<i className={'time-sort ' + (this.state.sortType == 3 ? 'time-sort-add' : this.state.sortType == 2 ? 'time-sort-dec' : '')}></i></b></th>
                                <th width='115'>操作</th>
                                <th width='20'></th>
                            </tr>
                        </thead>
                        <tbody>
                            {this.state.NewsList.map((item, idx) => {
                                if (item.beEduPush == '1' && item.newsCoverPath != '') {
                                    if (!item.newsCoverPath.toLowerCase().includes('https://')) {
                                        item.newsCoverPath = systemInfo.governmentWebUrl + '/' + item.newsCoverPath
                                    }
                                }
                                return <tr key={idx} onClick={(e) => { this.OpenNewsContent(e, item.newsId, item.userId, item.releaseStatus) }}>
                                    <td>
                                        {item.newsCoverPath?.length > 0 ? <img className='News-bg' src={item.newsCoverPath} alt="图片丢失" /> : <i className='News-bg News-bg1'></i>}
                                        <span><b title={item.newsTitle}>{item.newsTitle}</b>
                                        </span>{item.releaseStatus == 1 ? <b className='new-type new-publish'> 已发布</b> : <b className='new-type new-unPublish'>未发布</b>}<i className='new-line'></i><b className="new-type">{item.newsTypeName}</b></td>
                                    <td>{item.userName}</td>
                                    <td>{item.releaseStatus == 1 ? item.releaseTime : '--'}</td>
                                    <td>{item.releaseStatus == 1 ? item.readCount + '次' : '--'}</td>
                                    <td>
                            
                                        {
                                            item.releaseStatus == 0 ?
                                            <span>
                                                <b onClick={(e) => { this.EditNews(e, item.newsId) }}><i></i>编辑</b>
                                                <i></i><b onClick={(e) => { this.alertAQuestion(e, item.newsId, idx, item.newsTitle) }}><i></i>删除</b>
                                            </span> :
                                            <b className='withdraw' onClick={(e) => { this.questionCallback(e, item.newsId, idx, item.newsTitle) }}><i></i>撤回</b> 
                                        }
                                    </td>
                                    <td></td>
                                </tr>
                            })}
                        </tbody>
                    </table> : <div className='empty-div'> <i className='img-ig'></i><p style={{ 'color': '#bbb' }}>暂无您想要的新闻资讯哦~</p></div>}
                    
                </div>
                {
                    total > 10 ?
                        <div className="news-Pagination">
                            <LgPaginationA
                                total={Math.ceil(total / pageSize)}
                                size="normal"
                                currentPage={PageIndex}
                                onChangePage={this.changePageA}
                            ></LgPaginationA>
                        </div>
                        : ''
                }
                {
                    this.state.visible ?
                        <CreateNews getNewType={()=>this.getTypeList()} reloadType={this.reloadType} visible={this.state.visible} hideModal={this.hideModal} NoticeMain={this.state.NoticeMain} changeNoticeList={this.onChangePage} NewsTitle={this.state.NewsTitle} flashNews={() => this.getNewsList()} ></CreateNews>
                        : ''
                }
                <Alert message={this.state.message} newsName={newsName} isOpen={this.state.isOpen} chooseFn={(data) => { this.ChangeNewsFn(data) }}></Alert>
            </div>
        )
    }
}
export default Newslists;